package com.vancouver.knows.business.service.impl;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.pangu.AMApplication;
import com.pangu.bean.PageableResult;
import com.pangu.service.AHttpRequestService;
import com.pangu.service.ActionException;
import com.pangu.service.impl.ProtocolWrap;
import com.pangu.util.BitmapUtil;
import com.pangu.util.network.NetworkInfoParser;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.vancouver.knows.business.bean.BusinessRateInfo;
import com.vancouver.knows.business.bean.CityDiscountDetailInfo;
import com.vancouver.knows.business.bean.CityNewsDetailInfo;
import com.vancouver.knows.business.bean.CommentInfo;
import com.vancouver.knows.business.bean.DiscountInfo;
import com.vancouver.knows.business.bean.EditUserInfo;
import com.vancouver.knows.business.bean.EventDetailInfo;
import com.vancouver.knows.business.bean.ForgotPasswordInfo;
import com.vancouver.knows.business.bean.ModifyPasswordInfo;
import com.vancouver.knows.business.bean.NameValuePair;
import com.vancouver.knows.business.bean.PostPrivacySettingInfo;
import com.vancouver.knows.business.bean.SplashAdInfo;
import com.vancouver.knows.business.bean.UploadedUserPostDetailInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.bean.UserPostDetailInfo;
import com.vancouver.knows.business.bean.UserRegisterInfo;
import com.vancouver.knows.business.bean.VersionInfo;
import com.vancouver.knows.business.cache.PersistentCacheManager;

/**
 * 处理远程资源 Created by cxlin
 */
public class BHttpService extends AHttpRequestService {

	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	public static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
	public static final String TAG = BHttpService.class.getSimpleName();
	// 接口服务域名 测试服
	//public static final String DOMAIN = "api.vanknow.com/2.0.1/";
	// 接口服务域名 正式服
	public static final String DOMAIN = "api.vancoolver.ca/2.0.1/";

	// 获得服务关联的协议工厂
	private BProtocolFactory bProtocolFactory;

	public BHttpService(AMApplication imContext, BProtocolFactory bProtocolFactory) {
		super(imContext, TAG);
		this.bProtocolFactory = bProtocolFactory;
	}

	@Override
	protected String getDefaultHostUrl() {
		return DOMAIN;
	}

	private ProtocolWrap createProtocolWrap(List<NameValuePair> data){
		ProtocolWrap pw = new ProtocolWrap();
		JSONObject jsonObject = new JSONObject();
		for (NameValuePair param: data) {
			jsonObject.put(param.getName(),param.getValue());
		}
		RequestBody body = RequestBody.create(JSON, jsonObject.toJSONString());
		pw.setPostBody(body);
		pw.setIsHttps(true);

		return pw;
	}

	private ProtocolWrap createFilterProtocolWrap(List<NameValuePair> data) {
		ProtocolWrap pw = new ProtocolWrap();
		JSONObject jsonObject = new JSONObject();
		for (NameValuePair param: data) {
			if (param.getName().equals("filter_args")) {
				jsonObject.put(param.getName(), com.alibaba.fastjson.JSON.parseObject(param.getValue()));
			} else {
				jsonObject.put(param.getName(),param.getValue());
			}
		}
		RequestBody body = RequestBody.create(JSON, jsonObject.toJSONString());
		pw.setPostBody(body);
		pw.setIsHttps(true);

		return pw;
	}

	private ProtocolWrap createDeleteImagesProtocolWrap(List<NameValuePair> data) {
		ProtocolWrap pw = new ProtocolWrap();
		JSONObject jsonObject = new JSONObject();
		for (NameValuePair param: data) {
			if (param.getName().equals("images_array")) {
				jsonObject.put(param.getName(), com.alibaba.fastjson.JSON.parseArray(param.getValue()));
			} else {
				jsonObject.put(param.getName(),param.getValue());
			}
		}
		RequestBody body = RequestBody.create(JSON, jsonObject.toJSONString());
		pw.setPostBody(body);
		pw.setIsHttps(true);

		return pw;
	}

	/**
	 * 查询城事列表
	 * @return
	 * @throws ActionException
	 */
	public PageableResult fetchCityNews(List<NameValuePair> datas)
			throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchCityNewsHandler handler = new FetchCityNewsHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	/**
	 * 用户登录
	 * @param email 邮箱
	 * @param phone 手机号
	 * @param password 密码
	 * @param gcmToken token
	 * @return
	 * @throws ActionException
	 */
	public UserInfo userLogin(String email, String phone, String password, String gcmToken) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.getLoginRequest(email, phone, password, gcmToken);
		byte[] result = requestServiceResource(protocolWrap);
		UserInfoHandler handler = new UserInfoHandler();
		handler.parserJson(result);
		return handler.getUserInfo();
	}

	/**
	 * 查询用户
	 * @param userID  用户id
	 * @return
	 * @throws ActionException
	 */
	public UserInfo queryUserInfo(String userID) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.getQueryUserInfoRequest(userID);
		byte[] result = requestServiceResource(protocolWrap);
		QueryUserInfoHandler handler = new QueryUserInfoHandler();
		handler.parserJson(result);
		return handler.getUserInfo();
	}

	/**
	 * 点赞
	 * @throws ActionException
     */
	public void userUpvote(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 删除用户点赞
	 * @return
	 */
	public void userDeleteUpvote(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 查询活动列表
	 * @return
	 */
	public PageableResult fetchEvents(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchEventsHandler handler = new FetchEventsHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	/**
	 * 修改密码
	 * @param phone 手机号
	 * @param email 邮箱
	 * @return
	 * @throws ActionException
	 */
	public ForgotPasswordInfo forgotPassword(String phone, String email) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.getForgotPasswordRequest(phone, email);
		byte[] result = requestServiceResource(protocolWrap);
		ForgotPasswordHandle handler = new ForgotPasswordHandle();
		handler.parserJson(result);

		return handler.getForgotPasswordInfo();
	}

	/**
	 * 修改密码
	 * @param phone 手机号
	 * @param email 邮箱
	 * @param verification  6位数验证码
	 * @param userPassword 用户输入的新密码
	 * @return
	 * @throws ActionException
	 */
	public ModifyPasswordInfo modifyPassword(String phone, String email, String verification, String userPassword)
			throws ActionException {

		ProtocolWrap protocolWrap = bProtocolFactory.getModifyPasswordRequest(phone, email, verification, userPassword);
		byte[] result = requestServiceResource(protocolWrap);
		ModifyPasswordHandle handler = new ModifyPasswordHandle();
		handler.parserJson(result);

		return handler.getModifyPasswordInfo();
	}

	/**
	 * 查询活动详情
	 * @return
	 */
	public EventDetailInfo fetchEventDetail(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchEventDetailHandler handler = new FetchEventDetailHandler();
		handler.parserJson(result);

		return handler.getEventDetailInfo();
	}

	/**
	 * 用户关注
	 * @return
	 */
	public void userFollow(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 删除用户关注
	 * @return
	 */
	public void userDeleteFollow(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 邮箱验证码
	 * @param email 邮箱
	 * @throws ActionException
	 */
	public void emailSendSecurityCode(String email) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.emailSendSecurityCode(email);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);

	}

	/**
	 * 邮箱注册
	 * @param email 邮箱
	 * @param verificationCode 验证码
	 * @param userNickName 昵称
	 * @param password 密码
	 * @return
	 * @throws ActionException
	 */
	public UserRegisterInfo emailUserRegister(String email, String verificationCode, String userNickName,
			String password) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.emailUserRegister(email, verificationCode, userNickName, password);
		byte[] result = requestServiceResource(protocolWrap);
		UserRegisterHandle handler = new UserRegisterHandle();
		handler.parserJson(result);

		return handler.getUserRegisterInfo();

	}

	/**
	 * 获取手机验证码
	 * @param phone 手机号
	 * @throws ActionException
	 */
	public void phoneSendSecurityCode(String phone) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.phoneSendSecurityCode(phone);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);

	}

	/**
	 * 手机注册
	 * @param phone 手机号码
	 * @param verificationCode 验证吗
	 * @param userNickName 用户昵称
	 * @param password 密码
	 * @return
	 * @throws ActionException
	 */
	public UserRegisterInfo phoneUserRegister(String phone, String verificationCode, String userNickName,
			String password) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.phoneUserRegister(phone, verificationCode, userNickName, password);
		byte[] result = requestServiceResource(protocolWrap);
		UserRegisterHandle handler = new UserRegisterHandle();
		handler.parserJson(result);
		return handler.getUserRegisterInfo();
	}

	/**
	 * 查询城事详情
	 * @return
	 */
	public CityNewsDetailInfo fetchCityNewsDetail(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchCityNewsDetailHandler handler = new FetchCityNewsDetailHandler();
		handler.parserJson(result);

		return handler.getCityNewsDetailInfo();
	}

	public UserPostDetailInfo fetchUserPostDetail(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		FetchUserPostDetailInfoHandler handler = new FetchUserPostDetailInfoHandler();
		handler.parserJson(result);

		return handler.getUserPostDetailInfo();
	}

	/**
	 * 用户评论
	 * @return
	 */
	public CommentInfo userInsertComment(List<NameValuePair> datas)
			throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		UserInsertCommentHandler handler = new UserInsertCommentHandler();
		handler.parserJson(result);

		return handler.getCommentInfo();
	}

	/**
	 * 搜索
	 * @param keyWord 关键字
	 * @param fromType 搜索入口
	 * @param from 请求页
	 * @param size 请求页中个数
	 * @return
	 * @throws ActionException
	 */
	public HashMap<String, Object> userSearch(String keyWord, String fromType, String from, String size, String complete)
			throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userSearch(keyWord, fromType, from, size, complete);
		byte[] result = requestServiceResource(protocolWrap);
		SearchInfoHandle handler = new SearchInfoHandle();
		handler.parserJson(result);

		return handler.getResultMap();
	}

	/**
	 * 查询评论列表

	 * @return
	 */
	public PageableResult fetchComments(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchCommentsHandler handler = new FetchCommentsHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getCommentInfoList(), handler.getPageInfo());
	}

	/**
	 * 搜索总条数
	 * @return
	 * @throws ActionException
	 */
	public PageableResult userSearchTotal(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		SearchTotalInfoHandle handler = new SearchTotalInfoHandle();
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	/**
	 * 举报
	 * @return
	 */
	public void commentReport(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 首页
	 * @return
	 * @throws ActionException
	 */
	public HashMap<String, Object> homePage(String version) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.homePage(version);
		byte[] result = requestServiceResource(protocolWrap);
		HomePageHandle handler = new HomePageHandle();
		handler.parserJson(result);

		if (handler.checksum != null) {
			PersistentCacheManager.getInstance().putObject(PersistentCacheManager.HOMEPAGE_CHECKSUM_KEY, handler.checksum);
		}

		if (handler.isChecksumMatched) {
			return (HashMap<String, Object>) PersistentCacheManager.getInstance().getObject(PersistentCacheManager.HOMEPAGE_CACHE_KEY);
		} else {
			return handler.getResultMap();
		}
	}


	/**
	 * 公用接口（我的文章，我的评论，@我的评论，我的关注）
	 * @return
	 * @throws ActionException
	 */
	public PageableResult myArticleFollowAndComments(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		String pageType = "";
		for (NameValuePair nvp :datas) {
			if("page".equals(nvp.getName())){
				pageType = nvp.getValue();
			}
			break;
		}
		MyArticleHandle handler = new MyArticleHandle();
		handler.saveCurrentPageType(pageType);
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}



	/**
	 * 发表文章
	 * @param userId 用户id
	 * @param title 标题
	 * @param content 内容
	 * @param thumbnail 截图
	 * @param attachmentImage 上传的图片
	 * @param category 类型
     * @throws ActionException
     */
	public void userPostArticle(String userId, String title, String content, String thumbnail,
			List<String> attachmentImage, String category) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userPostArticle(userId, title, content, thumbnail,
				attachmentImage, category);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	public UploadedUserPostDetailInfo uploadUserPost(String userId, String postId, String content, String thumbnail, List<String> imgUrls,
													 String status, String category, String subcategory, String price, String city, String phone, String email) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.uploadUserPost(userId, postId, content, thumbnail, imgUrls, status, category, subcategory, price, city, phone, email);
		byte[] result = requestServiceResource(protocolWrap);
		UploadUserPostHandler handler = new UploadUserPostHandler();
		handler.parserJson(result);
		return handler.getUploadedUserPostDetailInfo();
	}

	/**
	 * 查询城惠列表

	 * @return
	 */
	public PageableResult fetchCityDiscounts(List<NameValuePair> datas)
			throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchCityDiscountsHandler handler = new FetchCityDiscountsHandler();
		handler.parserJson(result);

		if (handler.checksum != null) {
			PersistentCacheManager.getInstance().putObject(PersistentCacheManager.BUSINESS_HOME_CHECKSUM_KEY, handler.checksum);
		}

		if (handler.isChecksumMatched) {
			HashMap<String, Object> resultMap = (HashMap<String, Object>) PersistentCacheManager.getInstance().getObject(PersistentCacheManager.BUSINESS_HOME_CACHE_KEY);
			return new PageableResult(resultMap, handler.getPageInfo());
		} else {
			return new PageableResult(handler.getResultMap(), handler.getPageInfo());
		}
	}

	public PageableResult fetchUserPosts(List<NameValuePair> data) throws ActionException {

		ProtocolWrap protocolWrap = createFilterProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		FetchUserPostsHandler handler = new FetchUserPostsHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	public PageableResult getUserPosts(List<NameValuePair> data) throws ActionException {

		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		GetUserPostsHandler handler = new GetUserPostsHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	public HashMap<String, Object> fetchUserPostCategories(List<NameValuePair> data) throws ActionException {

		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		FetchUserPostCategoriesHandler handler = new FetchUserPostCategoriesHandler();
		handler.parserJson(result);

		return handler.getResultMap();
	}

	/**
	 *
	 * @param datas
	 * @return
	 * @throws ActionException
     */
	public PageableResult liveFeed(List<NameValuePair> datas)
			throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		LiveFeedHandler handler = new LiveFeedHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	/**
	 * 根据类型查询城惠列表

	 * @return
	 */
	public PageableResult fetchCtyDiscountCategory(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchCityDiscountsCategoryHandler handler = new FetchCityDiscountsCategoryHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getDiscountInfoList(), handler.getPageInfo());
	}

	/**
	 * 获取用户反馈，关于我们，用户使用协议
	 * @return
	 * @throws ActionException
     */
	public List<Object> myUserNotice(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		MyUserNoticeHandler handler = new MyUserNoticeHandler();
		handler.parserJson(result);
		return handler.getResultMap();
	}

	/**
	 * 获取图片cdn的token
	 * @return
	 * @throws ActionException
     */
	public HashMap<String, String> getCdnToken() throws ActionException {
		Response response = null;
		try {
			OkHttpClient client = NetworkInfoParser.getHttpConnector(imContext);
			String jsonStr = "{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\":{\"username\":\"zhidaomedia\", \"apiKey\":\"873831b002e7795f1b54091df2565b7d\"}}}";
			Request request = new Request.Builder().url("https://identity.api.rackspacecloud.com/v2.0/tokens/")
					.header("Content-type", "application/json")
					.post(RequestBody.create(BProtocolFactory.JSON, jsonStr)).build();
			response = client.newCall(request).execute();
			if (response.code() == 200) {
				TokenHandler handler = new TokenHandler();
				handler.parserJson(response.body().bytes());
				return handler.getMap();

			} else {
				return null;
			}
		} catch (Exception ex) {
			throw new ActionException(ActionException.OPERATE_ERROR, "operate error:" + ex.toString(), ex);

		} finally {
			if (response != null) {
				try {
					response.body().close();

				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 * 获取图片上传后的cdn地址
	 * @param url cdn空间地址
	 * @param token cdn的token
	 * @return
	 * @throws ActionException
     */
	public String getCdnUrl(String url, String token) throws ActionException {
		Response response = null;
		try {
			OkHttpClient client = NetworkInfoParser.getHttpConnector(imContext);
			Request request = new Request.Builder().url(url).header("X-Auth-Token", token).head().build();
			response = client.newCall(request).execute();
			if (response.code() == 204) {
				return response.header("X-Cdn-Ssl-Uri");

			} else {
				return null;
			}
		} catch (Exception ex) {
			throw new ActionException(ActionException.OPERATE_ERROR, "operate error:" + ex.toString(), ex);

		} finally {
			if (response != null) {
				try {
					response.body().close();

				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 *  上传图片
	 * @param token cdn token
	 * @param imgPath 图片本地路径
	 * @param url cdn空间地址
	 * @param isThumbnail determine if image uploaded is suppose to be a thumnail
	 * @throws ActionException
     */
	public void uploadImage(String token, String imgPath, String url, boolean isThumbnail) throws ActionException {
		Response response = null;
		try {
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgPath, options);

			if (isThumbnail) {
				options.inSampleSize = BitmapUtil.calculateInSampleSize(options, 200, 200);
			} else {
				options.inSampleSize = BitmapUtil.calculateInSampleSize(options, 640, 640);
			}
			options.inJustDecodeBounds = false;

			Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
			Bitmap orientedBitmap = BitmapUtil.rotateBitmap(imgPath, bitmap);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			orientedBitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
			byte[] byteArray = byteArrayOutputStream.toByteArray();

			OkHttpClient client = NetworkInfoParser.getHttpConnector(imContext);
			Request request = new Request.Builder().url(url).header("Content-Type", "image/jpeg")
					.header("X-Auth-Token", token).header("Content-Length", "" + byteArray.length)
					.put(RequestBody.create(BProtocolFactory.MEDIA_TYPE_JPEG, byteArray)).build();
			response = client.newCall(request).execute();
			if (response.code() == 201) {

			} else {
				throw new Exception();
			}
		} catch (Exception ex) {
			throw new ActionException(ActionException.OPERATE_ERROR, "operate error:" + ex.toString(), ex);

		} finally {
			if (response != null) {
				try {
					response.body().close();

				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 *  批量上传图片
	 * @param token cdn的token
	 * @param imgPaths 图片的本地路径集合
	 * @param urls cdn空间地址
	 * @throws ActionException
     */
	public void uploadImages(String token, List<String> imgPaths, List<String> urls) throws ActionException {
		for (int i = 0; i < urls.size(); i++) {
			if (i == 0) { // thumbnail
				uploadImage(token, imgPaths.get(i), urls.get(i), true);
			} else {
				uploadImage(token, imgPaths.get(i), urls.get(i), false);
			}
		}
	}

	/**
	 * 删除用户评论
	 * @return
	 */
	public void userDeleteComment(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 查询城惠详情
	 * @return
	 */
	public CityDiscountDetailInfo fetchDiscountDetail(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchDiscountDetailHandler handler = new FetchDiscountDetailHandler();
		handler.parserJson(result);
		return handler.getDiacountDetailInfo();
	}

	/**
	 * 用户图片更新
	 * @param userId 用户id
	 * @param imageUrl 需更新的图片url
	 * @return
	 * @throws ActionException
	 */
	public UserInfo userUploadImage(String userId, String imageUrl) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userUploadImage(userId, imageUrl);
		byte[] result = requestServiceResource(protocolWrap);
		UserInfoHandler handler = new UserInfoHandler();
		handler.parserJson(result);

		return handler.getUserInfo();
	}

	/**
	 *  用户评论星级
	 * @return
	 */
	public BusinessRateInfo userRateBusiness(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		UserRateBusinessHandler handler = new UserRateBusinessHandler();
		handler.parserJson(result);

		return handler.getBusinessRateInfo();
	}

	/**
	 * 添加用户GCM的token
	 * @param userId 用户id
	 * @param registrationId gcm注册id
	 * @param status 状态
	 * @param auid auid
	 * @return
	 */
	public void addUserToken(String userId, String registrationId, String status,String auid) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.addUserToken(userId, registrationId, status, auid);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 添加用户FCM的token
	 * @param userId
	 * @param fcmToken
	 * @throws ActionException
     */
	public void addUserToken(String userId, String fcmToken) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.addUserToken(userId, fcmToken);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 删除文章
	 * @return
	 */
	public void userDeleteArticle(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 * 上传推送设置
	 * @param userId 用户id
	 * @param postReminder 文章评论推送
	 * @param commentReminder at我的评论推送
	 * @param businessReminder 关注商家推送
	 * @throws ActionException
     */
	public void setMessageRemind(String userId, boolean postReminder, boolean commentReminder, boolean businessReminder)
			throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.setMessageRemind(userId, postReminder, commentReminder,
				businessReminder);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	/**
	 *  获取用户推送设置
	 * @param userId 用户id
	 * @return
	 * @throws ActionException
     */
	public Map userGetNotificationSetting(String userId) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userGetNotificationSetting(userId);
		byte[] result = requestServiceResource(protocolWrap);
		UserGetNotificationSettingHandler handler = new UserGetNotificationSettingHandler();
		handler.parserJson(result);
		return handler.getNotificationSertting();
	}

	/**
	 * 获取auid
	 * @param androidId
	 * @param imei
	 * @param adid
	 * @return
	 * @throws ActionException
     */
	public String userGetAuid(String androidId,String imei,String adid) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userGetAuid(androidId, imei, adid);
		byte[] result = requestServiceResource(protocolWrap);
		UserGetAuidHandler handler = new UserGetAuidHandler();
		handler.parserJson(result);
		return handler.getAuid();
	}

	/**
	 * 获取userIdHash
	 * @param userid
	 * @param auid
	 * @return
	 * @throws ActionException
	 */
	public String userHash(String userid,String auid) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userHash(userid, auid);
		byte[] result = requestServiceResource(protocolWrap);
		UserHashHandler handler = new UserHashHandler();
		handler.parserJson(result);
		return handler.getUserIdHash();
	}

	/**
	 * 版本更新
	 * @return
	 * @throws ActionException
	 */
	public VersionInfo updateVersion() throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.updateVersion();
		byte[] result = requestServiceResource(protocolWrap);
		VersionInfoHandler handler = new VersionInfoHandler();
		handler.parserJson(result);

		return handler.getVersionInfo();
	}

	/**
	 * 开屏广告
	 * @return
	 * @throws ActionException
     */
	public SplashAdInfo sendSplashAd() throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.sendSplashAd();
		byte[] result = requestServiceResource(protocolWrap);
		SplashAdInfoHandler handler = new SplashAdInfoHandler();
		handler.parserJson(result);

		return handler.getSplashAdInfo();
	}

	public List<DiscountInfo> homeMap(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		FetchHomeMapHandler handler = new FetchHomeMapHandler();
		handler.parserJson(result);

		return handler.getData();
	}

	public EditUserInfo editUserProfile(List<NameValuePair> datas) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(datas);
		byte[] result = requestServiceResource(protocolWrap);
		EditUserProfileHandler handler = new EditUserProfileHandler();
		handler.parserJson(result);

		return handler.getEditUserInfo();
	}

	public void resetPassword(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	public PostPrivacySettingInfo setListingsPrivacy(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		PostPrivacySettingHandler handler = new PostPrivacySettingHandler();
		handler.parserJson(result);

		return handler.getPrivacySetting();
	}

	public void renewUserPost(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	public PageableResult fetchMyUserPostComments(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		MyArticleHandle handler = new MyArticleHandle();
		handler.saveCurrentPageType(MyArticleHandle.USER_POSTED_COMMENTS);
		handler.parserJson(result);

		return new PageableResult(handler.getResultMap(), handler.getPageInfo());
	}

	public void uploadBusinessPhotos(String userId, String postId, List<String> imgUrls, String caption) throws ActionException {
		ProtocolWrap protocolWrap = bProtocolFactory.userBusinessPhotos(userId, postId, imgUrls, caption);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}

	public PageableResult fetchUserBusinessImages(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		FetchUserBusinessImagesHandler handler = new FetchUserBusinessImagesHandler();
		handler.parserJson(result);

		return new PageableResult(handler.getUserBusinessImages(), handler.getPageInfo());
	}

	public void deleteUserBusinessImages(List<NameValuePair> data) throws ActionException {
		ProtocolWrap protocolWrap = createDeleteImagesProtocolWrap(data);
		byte[] result = requestServiceResource(protocolWrap);
		EmptyHandler handler = new EmptyHandler();
		handler.parserJson(result);
	}
}
